import { _decorator, Component, Node, Vec2, Graphics, EventMouse, input, Input, Color, UITransform, Label, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('TestLine')
export class TestLine extends Component {
    @property(Graphics)
    private graphics: Graphics = null!; // 用于绘制线条的Graphics组件

    @property(Node)
    private pointLabel: Node = null!; // 提示文本的Label节点

    private startPoint: Vec2 | null = null; // 第一个点击位置
    private endPoint: Vec2 | null = null;   // 第二个点击位置
    private drawProgress: number = 0;    // 绘制进度 (0-1)
    private fadeProgress: number = 0;    // 消失进度 (0-1)
    private isDrawing: boolean = false;  // 是否正在绘制
    private isFading: boolean = false;   // 是否正在消失
    private drawSpeed: number = 0.2;     // 绘制速度 (秒)
    private fadeSpeed: number = 0.2;     // 消失速度 (秒)
    private fadeDelay: number = 0.1;     // 消失延迟时间 (秒)
    private fadeDelayTimer: number = 0;  // 消失延迟计时器
    private waveTime: number = 0;  // 波浪动画时间
    private waveSpeed: number = 50; // 波浪移动速度

    start() {
        // 确保有Graphics组件
        if (!this.graphics) {
            this.graphics = this.getComponent(Graphics);
            if (!this.graphics) {
                this.graphics = this.addComponent(Graphics);
            }
        }

        // 监听鼠标点击事件
        input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
    }

    onMouseDown(event: EventMouse) {
        const mousePos = this.getMousePosition(event);

        if (!this.startPoint) {
            // 第一次点击，记录起始点
            this.startPoint = mousePos;
            this.showPointLabel(mousePos, "起点"); // 显示起点提示
        } else {
            // 第二次点击，记录终点并绘制线条
            this.endPoint = mousePos;
            this.showPointLabel(mousePos, "终点"); // 显示终点提示
            // 开始动画绘制
            this.startDrawingAnimation();
        }
    }

    // 获取鼠标在世界坐标中的位置
    private getMousePosition(event: EventMouse): Vec2 {
        const canvas = this.node.parent; // 获取父节点（Canvas）
        const mousePos = event.getLocation(); // 获取鼠标位置
        const worldPos = canvas.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(mousePos.x, mousePos.y, 0)); // 转换为节点空间
        return new Vec2(worldPos.x, worldPos.y);
    }

    // 开始绘制动画
    private startDrawingAnimation() {
        this.drawProgress = 0;
        this.fadeProgress = 0;
        this.isDrawing = true;
        this.isFading = false;
        this.fadeDelayTimer = 0;
    }

    // 绘制波浪线（带进度）
    private drawWavyLine(start: Vec2, end: Vec2, drawProgress: number, fadeProgress: number) {
        this.graphics.clear();
        this.graphics.lineWidth = 10;
        this.graphics.strokeColor = new Color(255, 0, 0, 255);

        // 计算当前绘制终点
        const currentEnd = new Vec2(
            start.x + (end.x - start.x) * drawProgress,
            start.y + (end.y - start.y) * drawProgress
        );

        // 计算当前消失起点
        const fadeStart = new Vec2(
            start.x + (end.x - start.x) * fadeProgress,
            start.y + (end.y - start.y) * fadeProgress
        );

        // 如果已经完全消失，不需要绘制
        if (fadeProgress >= drawProgress) {
            return;
        }

        // 计算方向向量
        const dx = end.x - start.x;
        const dy = end.y - start.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const currentDistance = distance * drawProgress;

        // 根据距离计算波浪数量
        const baseLength = 200;
        const waveCount = Math.max(1, Math.round(distance / baseLength));

        // 生成波浪形的点
        const points: Vec2[] = [];
        const segments = 50;
        const amplitude = 10;

        for (let i = 0; i <= segments; i++) {
            const t = (i / segments) * drawProgress;
            if (t > 1 || t < fadeProgress) continue;

            const x = start.x + dx * t;
            const y = start.y + dy * t;

            const angle = Math.atan2(dy, dx);
            const perpX = Math.cos(angle - Math.PI / 2);
            const perpY = Math.sin(angle - Math.PI / 2);

            // 添加时间因子来使波浪动起来
            const wave = Math.sin(t * Math.PI * 2 * waveCount + this.waveTime) * amplitude;
            // 可以添加第二个波形来使效果更丰富
            const wave2 = Math.sin(t * Math.PI * 4 * waveCount - this.waveTime * 0.5) * (amplitude * 0.5);
            const finalWave = wave + wave2;
            
            points.push(new Vec2(
                x + perpX * finalWave,
                y + perpY * finalWave
            ));
        }

        // 绘制波浪线
        if (points.length > 1) {
            this.graphics.moveTo(points[0].x, points[0].y);
            
            for (let i = 0; i < points.length - 1; i++) {
                const current = points[i];
                const next = points[i + 1];
                const mid = new Vec2(
                    (current.x + next.x) / 2,
                    (current.y + next.y) / 2
                );

                if (i === 0) {
                    this.graphics.quadraticCurveTo(current.x, current.y, mid.x, mid.y);
                } else {
                    this.graphics.quadraticCurveTo(current.x, current.y, mid.x, mid.y);
                }
            }

            // 连接到当前终点
            this.graphics.quadraticCurveTo(
                points[points.length - 1].x,
                points[points.length - 1].y,
                currentEnd.x,
                currentEnd.y
            );
        }

        this.graphics.stroke();
    }

    // 显示提示文本
    private showPointLabel(position: Vec2, text: string) {
        const label = this.pointLabel.getComponent(Label);
        if (label) {
            label.string = text; // 设置提示文本
            this.pointLabel.setPosition(position.x, position.y); // 设置Label位置
            this.pointLabel.active = true; // 显示Label
        }

        // 隐藏Label一段时间后
        this.scheduleOnce(() => {
            this.pointLabel.active = false; // 隐藏Label
        }, 2); // 2秒后隐藏
    }

    update(deltaTime: number) {
        // 更新波浪时间
        this.waveTime += deltaTime * this.waveSpeed;

        if (this.startPoint && this.endPoint) {
            if (this.isDrawing) {
                // 更新绘制进度
                this.drawProgress += deltaTime / this.drawSpeed;
                
                if (this.drawProgress >= 1) {
                    this.drawProgress = 1;
                    this.isDrawing = false;
                    this.fadeDelayTimer = 0;
                }
            } else if (!this.isFading) {
                this.fadeDelayTimer += deltaTime;
                if (this.fadeDelayTimer >= this.fadeDelay) {
                    this.isFading = true;
                }
            } else {
                this.fadeProgress += deltaTime / this.fadeSpeed;
                
                if (this.fadeProgress >= 1) {
                    this.fadeProgress = 1;
                    this.isFading = false;
                    this.startPoint = null;
                    this.endPoint = null;
                    this.graphics.clear();
                    return;
                }
            }

            this.drawWavyLine(this.startPoint, this.endPoint, this.drawProgress, this.fadeProgress);
        }
    }
}